<template>
	<view class="container-conversation">
		<u-navbar title="聊天" :is-back="false" :autoBack="false">
			<view slot="right" @tap="toMess">

				<view class="icon-wrap" style="position: relative;">
					<u-icon class="nav-icon-right" name="chat" color="#666" size="48"></u-icon>
					<u-badge :isDot="true" type="error" v-if="userinfo.notice"></u-badge>
				</view>
			</view>
		</u-navbar>
		<u-sticky :enable="enable">
			<view class="tab-list" style="">
				<view @click="tabClick(index)" :class="num==index?'active':'noactive'" v-for="(item,index) in tablist">
					{{item}}
				</view>
			</view>
		</u-sticky>

		<view v-if="num==0">
			<view-NoData v-if="Tlist.length==0">

			</view-NoData>
			<!-- 推荐列表 -->
			<view class="">
				<view class="">
					<view style="box-sizing: border-box; background: #fff; margin-top: 4px; padding: 10px;"
						v-for="item in Tlist" @tap="goRoute(item,item.id)">
						<view style="display: flex; align-items: center;position: relative;">
							<image style="width: 96rpx;height: 96rpx;border-radius: 14rpx;" :src="item.avatar">
							</image>
							<view style="margin-left: 10px;">
								<view style="font-size: 32rpx; line-height: 53rpx; color: #333;">
									{{item.nickname}}
								</view>
								<view
									style="line-height: 40rpx;font-size: 28rpx;font-family: 'PingFangSC-Regular';color: #999999; display: flex;">
									{{item.bio==''?'该用户太懒，什么都没说~~~':item.bio}}
								</view>
							</view>
						</view>
						<!-- <TUI-conversation-item :data-type="item.type" :conversation="item">
						</TUI-conversation-item> -->
					</view>
				</view>
			</view>
		</view>
		<view v-if="num==1">
			<view-NoData v-if="conversationList.length==0">

			</view-NoData>
			<view class="scroll-box">
				<view class="uni-list margintop-bar">
					<!-- <view v-for="item in conversationList" :key="item.conversationID"
						@tap="handleRoute(item,item.conversationID)">
						<TUI-conversation-item :data-type="item.type" :conversation="item">
						</TUI-conversation-item>
					</view> -->
					<lsDrag :list.sync="conversationList" listKey="name" @dragSortChange="dragSortChange" @editItem="editItem"
						@deleteItem="deleteItem" />
				</view>
			</view>

		</view>

		<image @click="search"
			style="position: fixed; z-index: 1; width: 80px; height: 80px; bottom: 150px; right: 20px;"
			src="/static/pp.png"></image>
		<!-- <view class="bottom-back">
        <view class="bottom-area">
            <view v-if="showSelectTag" class="conversation-bubble" @tap.stop="handleEditToggle">
                <view v-for="(item, index) in array" :key="index" class="picker" :data-name="item.name" @tap="handleOnTap">
                    {{item.name}}
                </view>
            </view>
            <image @tap="showMore" class="btn-show-more" src="/static/static/assets/add.svg"></image>
        <view @tap="learnMore" class="im-link">了解更多IM功能</view>
      </view>
    </view> -->
	</view>
</template>
<!-- 这里有个加载的补丁逻辑待优化，页面向SDK请求conversationList的时候会有时延，
造成页面的一个抖动，这里加一个if逻辑打一个补丁，后续继续优化 -->
<script>
	import logger from '../../../utils/logger';
	import TUIConversationItem from "../../../components/tui-conversation/conversation-item/index";
	import TUIMessageList from "../../../components/tui-chat/message-list/index";
	import lsDrag from '../../../components/gzz-option-list/option-list.vue'
	import {
		topUserList,
		checkPayChat,
		createChatOrder,
		delDialog
	} from '@/common/config/chat.js'
	import {
		genTestUserSig
	} from '@/debug/GenerateTestUserSig.js'

	export default {
		data() {

			return {
				userinfo: {},
				enable: true,
				tablist: [
					'推荐', '聊天列表'
				],
				Tlist: [],
				num: 0,
				page: 0,
				conversationList: [],
				showSelectTag: false,
				array: [{
					name: '发起会话'
				}, {
					name: '发起群聊'
				}, {
					name: '加入群聊'
				}],
				item: {}
			};
		},

		components: {
			TUIConversationItem,
			TUIMessageList,
			lsDrag
		},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad() {

		},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			uni.$TUIKit.off(uni.$TUIKitEvent.SDK_READY, this.onConversationListUpdated);
		},
		onShow() {
			this.topUserList()
			this.conversationList=[]
			// this.Tlist=[]
			// console.log(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED,this.onConversationListUpdated,'uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED')
			// 登入后拉去会话列表
			// uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);
			// uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED,this.onConversationListUpdated,'uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED'
			// TIM_DECL int TIMConvGetTotalUnreadMessageCount(TIMCommCallback cb, const void* user_data);
			this.enable = true
			setTimeout(()=>{
				this.getConversationList();
			},500)

			// this.onConversationListUpdated()
			const token = uni.getStorageSync('token')
			if (token) {
				this.getuserinfo.getuserinfo(uni.getStorageSync('userdata').id).then((res) => {
					if (res) {
						this.userinfo = res.data
					}
				})
			}
		},
		onHide() {
			this.enable = false
		},
		methods: {
			// 拖拽排序触发
			dragSortChange(e) {
				console.log('drag', e)
				// e.frontData 插到谁后面
				// e.data 操作的数据
				let list = [...this.list]
				if (e.frontData) {
					let before = e.frontData.sort
					let after = e.data.sort
					list.splice(before, 0, list.splice(after, 1)[0])
				} else {
					list.splice(0, 0, list.splice(e.data.sort, 1)[0])
				}
				this.list = [...list]
			},
			// 编辑方法
			editItem(item) {
				// 做对应的编辑操作，如弹编辑框等
				console.log('edit item', item)
			},
			// 删除方法
			deleteItem(itemed) {
				// 做对应的删除操作，如调用删除接口等
				// console.log('delete item',item)
				var item=itemed.items
				// 先退出登录聊天列表
				this.login()
				delDialog({user_id:item.userProfile.userID}).then(res=>{
					console.log(res,'删除')
					this.conversationList.splice(itemed.index, 1)
					// 重新登录
					const userID = String(uni.getStorageSync('userdata').id)
					const userSig = genTestUserSig(userID).userSig
					// // 腾讯云用户信息
					app.globalData.userInfo = {
						userSig,
						userID,
					}
				})
			},
			login() {
				const userID = uni.getStorageSync('userID')
				const userSig = uni.getStorageSync('userSig')
				console.log('腾讯云登出', userID)
			
				uni.$TUIKit.logout({
						userID,
						userSig
					})
					.then(function(imResponse) {
						console.log('登出成功', imResponse.data); // 登录成功
						// if (imResponse.data.repeatLogin === true) {
						// 	// 标识帐号已登录，本次登录操作为重复登录。v2.5.1 起支持
						// 	console.log(imResponse.data.errorInfo);
						// }
					})
					.catch(function(imError) {
						console.warn('login error:', imError); // 登录失败的相关信息
					})
			
			},
			goRoute(item, id) {
				this.item = item
				if (item.price > 0) {
					this.checkPayChat(id)
				} else {
					uni.navigateTo({
						url: '/pages/TUI-Chat/chat?conversationID=C2C' + id
					})
				}

			},
			// 判断当前用户手否被购买过
			checkPayChat(data) {
				let datas = {
					uid: data
				}
				checkPayChat(datas).then((res) => {
					console.log(res, '返回数据')
					if (res.data.code == 0) {
						this.createChatOrder(datas)
					} else {
						uni.navigateTo({
							url: '/pages/TUI-Chat/chat?conversationID=C2C' + data
						})
					}
				})
			},
			// 购买推荐用户
			createChatOrder(data) {
				createChatOrder(data).then((res) => {
					if (res.data.code == 1) {
						console.log(res, '返回的订单数据')
						uni.navigateTo({
							url: `/pages/pay/pay?orderId=${res.data.data.order_no}&price=${this.item.price}&type=cart&cartid=${JSON.stringify(data)}`
						})
					}
				})
			},
			topUserList() {
				topUserList({}).then((res) => {
					console.log(res, '推荐列表')
					this.Tlist = res.data.data
				})
			},
			toMess() {
				uni.navigateTo({
					url: '/pages/message/message'
				})
			},
			search() {
				uni.navigateTo({
					url: '/pages/Search/Search'
				})
			},
			handleRoute(item, id) {
				console.log(item, 'handleRoute')
				// return false
				const url = `../../TUI-Chat/chat?conversationID=${id}&userid=${item.userProfile.userID}`;
				uni.navigateTo({
					url
				});
			},
			onConversationListUpdated(event) {
				console.log(event.data, 'event.dataevent.dataevent.dataevent.data')
				logger.log('TUI-conversation | onConversationListUpdated  |ok');
				this.setData({
					conversationList: event.data
				});
				console.log(this.conversationList,'232323456')
				var num = 0
				event.data.forEach((item) => {
					num += item.unreadCount
				})
				console.log(num.toString(), 'ggggg')
				if (num > 0) {
					uni.setTabBarBadge({
						index: 1,
						text: num.toString()
					})
				}
				if (num == 0) {
					uni.setTabBarBadge({
						index: 1,
						text: 0
					})
				}
			},

			getConversationList() {
				// 登入后拉去会话列表
				uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);
				uni.$TUIKit.getConversationList().then(imResponse => {
					console.log(imResponse, 'imResponse666666666666666666666666666666666666666')
					logger.log(
						`TUI-conversation | getConversationList | getConversationList-length: ${imResponse.data.conversationList.length}`
					);
					var num = 0
					imResponse.data.conversationList.forEach((item) => {
						num += item.unreadCount
					})
					console.log(num.toString(), 'ggggg')
					if (num > 0) {
						uni.showTabBarRedDot({
							index: 1,
						})
						uni.setTabBarBadge({
							index: 1,
							text: num.toString()
						})
					}
					if (num == 0) {
						console.log('4444444')
						uni.hideTabBarRedDot({
							index: 1
						})
						// uni.setTabBarBadge({
						//   index: 1,
						//   text:0
						// })
					}
					this.setData({
						conversationList: imResponse.data.conversationList
					});
				});
				// console.log(imResponse.data.conversationList,'imResponse.data.conversationList')
			},

			showMore() {
				this.setData({
					showSelectTag: !this.showSelectTag
				});
			},

			learnMore() {
				uni.navigateTo({
					url: '../../TUI-User-Center/webview/webview?url=https://cloud.tencent.com/product/im'
				});
			},

			handleOnTap(event) {
				this.setData({
					showSelectTag: false
				}, () => {
					switch (event.currentTarget.dataset.name) {
						case '发起会话':
							this.$createConversation();
							break;

						case '发起群聊':
							this.$createGroup();
							break;

						case '加入群聊':
							this.$joinGroup();

						default:
							break;
					}
				});
			},

			goHomePage() {
				// uni.navigateTo 不能跳转到 tabbar 页面，使用 uni.switchTab 代替
				uni.switchTab({
					url: '../../TUI-Index/index'
				});
			},

			handleEditToggle() {
				this.setData({
					showSelectTag: false
				});
			},

			$createConversation() {
				uni.navigateTo({
					url: '../create-conversation/create'
				});
			},

			$createGroup() {
				uni.navigateTo({
					url: '../../TUI-Group/create-group/create'
				});
			},

			$joinGroup() {
				uni.navigateTo({
					url: '../../TUI-Group/join-group/join'
				});
			},
			tabClick(index) {
				this.num = index
				if (index == 0) {
					this.topUserList()
				}
				// this.page = 0
				// this.groups = []
			},

		}
	};
</script>
<style scoped>
	@import "./conversation.css";

	.nav-icon-right {
		padding: 7px 12px 7px 7px;
	}

	.tab-list {
		display: flex;
		background: #f7f7f7;
		width: 100%;
		height: 46px;
		line-height: 46px;
	}

	.noactive {
		margin-left: 20px;
		font-size: 14px
	}

	.active {
		font-size: 16px;
		margin-left: 20px;
		font-weight: bold;
		position: relative;
	}

	.active::before {
		content: '';
		position: absolute;
		z-index: 1;
		width: 100%;
		height: 4px;
		background: #EA9B37;
		border-radius: 12px;
		left: 0;
		bottom: 0;
	}
</style>
